#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2020/11/24 19:43
# @Author  : Wang Feng
# @FileName: jenkins.py
# @Software: PyCharm
import json
import uuid

import jenkins

# server = jenkins.Jenkins('http://10.51.42.13:8080/jenkins', username='tester123', password='tester123')
# print(json.dumps(server.get_job_info('军民融合_test_param')))
# print(json.dumps(server.get_build_info('军民融合_test_param', 46)))
# print(Random().randrange(start=1, stop=1000))
from app import scheduler
from app.models import TestTask
from app.settings import JENKINS_URI, JENKINS_USERNAME, JENKINS_PASSWORD

server = jenkins.Jenkins(JENKINS_URI, username=JENKINS_USERNAME, password=JENKINS_PASSWORD)


# print(json.dumps(server.get_queue_info()))


# print(json.dumps(server.get_queue_info()))


# print(type(server.get_queue_info()))
# queue_list = server.get_queue_info()
# if queue_list is not None:
#     job_no_list = []
#     for queue in queue_list:
#         actions = queue.get('actions')
#         parameters = actions[0].get('parameters')
#         for parameter in parameters:
#             if parameter['name'] == 'job_no':
#                 job_no_list.append(parameter['value'])


def is_job_no_in_queue(job_no):
    """
    判断job_no是否在queue队列中
    如果存在则处于padding状态
    不存在说明已经在执行或已经执行完成
    :param job_no:
    :return:
    """
    queue_list = server.get_queue_info()
    print(json.dumps(queue_list))
    if queue_list is not None:
        job_no_list = []
        for queue in queue_list:
            actions = queue.get('actions')
            parameters = actions[0].get('parameters')
            for parameter in parameters:
                if parameter['name'] == 'task_id':
                    job_no_list.append(parameter['value'])
        if job_no in job_no_list:
            return True
    return False


def get_last_build_job(name, number):
    """
    获取最后执行的几个任务id
    :param name: 工程名称
    :param number: 构建数量
    :return:
    """
    job_info = server.get_job_info(name)
    builds = job_info['builds'][:number]
    # print(len(builds))
    build_number = []
    for build in builds:
        # print(build)
        build_number.append(build['number'])
    return build_number


def get_build_info(name, build_number, job_no):
    """
    获取工程构建信息
    :param name: 工程名称
    :param build_number: 构件number
    :param job_no: 任务no
    :return:
    """
    # print(json.dumps(server.get_build_info(name, build_number)))
    # print()
    # print()
    # print()
    # print()
    build_info = server.get_build_info(name, build_number)
    actions = build_info.get('actions')
    if actions is not None:
        # print(build_number)
        # print(actions)
        parameters = actions[0].get('parameters')
        if parameters is not None:
            build_job_no = parameters[0].get('value')
            print(build_job_no)
            if build_job_no == job_no:
                number = build_info.get('number')
                result = build_info.get('result')
                duration = build_info.get('duration')
                timestamp = build_info.get('timestamp')
                fullDisplayName = build_info.get('fullDisplayName')
                print(number, result, duration, timestamp, fullDisplayName)
                return number, result, duration, timestamp, fullDisplayName
    return False


def build_job(task_name, tests):
    uid = str(uuid.uuid4())
    suid = ''.join(uid.split('-'))
    try:
        queue_id = server.build_job('public_test', {'task_name': task_name, 'task_id': suid, 'test_cases': tests})
    except Exception as e:
        print(e)
    else:
        with scheduler.app.app_context():
            if queue_id is not None:
                testtask = TestTask()
                testtask.task_name = task_name
                testtask.task_id = suid
                testtask.result = 'pending'
                testtask.save()


if __name__ == '__main__':
    pass
    # print(is_job_no_in_queue('74ab28e2ac4847798a8b42f8fc354481'))
    # print(get_last_build_job('军民融合_test_param', 5))
    print(get_build_info('军民融合_test_remote', 58, '0e00638b59d34942b31cd9807fc9d1e7'))
    # print(json.dumps(server.get_queue_info()))
    # print(json.dumps(server.get_build_info('军民融合_test_remote', 21)))
